import { PageContainer } from '@ant-design/pro-layout';
import { Drawer, message, Popconfirm, Space, Table, Upload} from 'antd';
import ProTable, { ActionType, EditableProTable } from '@ant-design/pro-table';
import React, { useState} from 'react';
import type { ProColumns } from '@ant-design/pro-table';
import { useRef } from 'react';
import { findOrderSettlementList,findServiceDealer,editSettlementDetail ,findDetailBySettlementId,setStatus} from './service';
import ProForm, { DrawerForm, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea} from '@ant-design/pro-form';
import { accAdd, accMul, accSub, manufacturerOption, moneyFormat } from '@/utils/utils';
import UpDownLabel from '@/components/Common/UpDownLabel';

export default () => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([0]);
  const [proData,setProData] = useState<any>([]);
  const formRef = useRef<any>();
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef<ActionType>();
  const [activeKey,setActiveKey] = useState("tab1");
  const [services,setServices] = useState<any>([]);
  const [vouchern,setVouchern] = useState<any>([{id:'JXS4252',name:'合肥**医疗科技有限公司'},{id:'JXS4253',name:'合肥**医疗科技有限公司'}]);
  const [showService, setShowService] = useState(false);
  const [ticketAttList,setTicketAttList]= useState([]);
  const [showFile, setShowFile] = useState(false);
  const [showVouchern, setShowVouchern] = useState(false);
  const [currentRecord,setCurrentRecord] = useState<any>({});

  const handlePreview = async (file:any) => {
    window.open(file.url);
   };

  const sColumn: ProColumns[] = [
    {
      title:'名称',
      dataIndex: 'name',
    },
    {
      title:'联系方式',
      dataIndex: 'phone',
    },
    {
      title:'收款账户',
      dataIndex: 'account',
    },
    {
      title:'营业执照',
      valueType:'image',
      dataIndex: 'img1',
    },
    {
      title:'收款账户凭证',
      valueType:'image',
      dataIndex: 'img1',
    },
    {
      title: "操作",
      valueType: 'option',
      width:100,
      render: (text, record:any,_, action) => [
        <a key="select" onClick={()=>setShowService(false)}>选择</a>
      ]
    }
  ]
  const vColumn: ProColumns[] = [
   
    {
      title:'凭证代码',
      dataIndex: 'id',
    },
    {
      title:'客户名称',
      dataIndex: 'name',
    },
    {
      title: "操作",
      valueType: 'option',
      width:100,
      render: (text, record:any,_, action) => [
        <a key="file" onClick={()=>{
          setShowFile(true)
        }}>查看</a>,
        <a key="select" onClick={()=>setShowVouchern(false)}>选择</a>
      ]
    }
  ]
  const pColumns: ProColumns[] = [
    {
      title: '产品名称',
      width: 100,
      ellipsis:true,
      dataIndex: 'productName',
      editable: false,
      renderText: (_, record: any) => {
        if (record.isGift == '1') {
          return `${record.productName}(赠品)`;
        }
        return record.productName;
      }
    }, {
      width: 80,
      ellipsis:true,
      title: '产品型号',
      dataIndex: 'productStandard',
      editable: false
    },
    {
      title: '订货数量',
      dataIndex: 'orderNum',
      editable:false,
      width: 70
    }, {
      title: '订单单价(元)',
      dataIndex: 'price',
      width: 90,
      editable:false,
    },
    {
      title: '实际单价(元)',
      dataIndex: 'a_price',
      valueType: 'money',
      formItemProps: (form, {
        rowIndex
      }) => {
        return {
          rules: [{
            required: true,
            message: '单价必填'
          }]
        };
      },
      width: 90,
    },
    {
      title: '订单总价(元)',
      dataIndex: 'o_t_price',
      editable:false,
      width: 90,
      renderText:(text,record:any)=>{
        return moneyFormat(accMul(Number(record.price), record.orderNum));
      }
    },
    {
      title: '实际总价(元)',
      dataIndex: 'a_t_price',
      editable:false,
      width: 90,
      renderText:(text,record:any)=>{
        return moneyFormat(accMul(Number(record.a_price), record.orderNum));
      }
    },
    {
      title: '订单差价(元)',
      dataIndex: 'diff_price',
      editable:false,
      width: 90,
      renderText:(text,record:any)=>{
        var t1 = accMul(Number(record.price), record.orderNum)
        var t2 = accMul(Number(record.a_price), record.orderNum)
        return moneyFormat(accSub(t2,t1));
      }
    },
    {
      title: '返利金额(元)',
      editable:false,
      dataIndex: 'rebate',
      width: 90,
      renderText:(text,record:any)=>{
        var t1 = accMul(Number(record.price), record.orderNum)
        var t2 = accMul(Number(record.a_price), record.orderNum)
        return moneyFormat(accMul(accSub(t2,t1),0.85));
      }
    },
  ]
  //表头信息以及表值设置
  const columns: ProColumns[] = [
    {
      title:'客户代码',
      dataIndex: 'dealerCode',
      width:100,
    },
    
    {
      title:'客户名称',
      dataIndex: 'dealerName',
      width:150,
      ellipsis:true,
    },
    {
      title:'订单号',
      dataIndex: 'orderNumber',
      width:130,
      ellipsis:true,
    },
    {
      title:'订单日期',
      dataIndex: 'oTime',
      valueType:'dateRange',
      hideInTable:true,
      width:110,
      ellipsis:true,
    },
    {
      title: '订单日期',
      dataIndex: 'orderTime',
      valueType:'date',
      ellipsis:true,
      width:110,
      hideInSearch:true,
    },
    {
      title: '当前服务商',
      dataIndex: 'serviceName',
      width:150,
      ellipsis:true,
    },
    {
      title: '结算日期',
      dataIndex: 'settlementTime',
      ellipsis:true,
      width:110,
      valueType:'date',
      hideInSearch:true,
      hideInTable:activeKey=='tab1'||activeKey=='tab4',
    },
    {
      title: '结算人',
      dataIndex: 'settlementPerson',
      ellipsis:true,
      width:100,
      hideInSearch:activeKey=='tab1'||activeKey=='tab4',
      hideInTable:activeKey=='tab1'||activeKey=='tab4',
    },
    {
      title: '结算日期',
      dataIndex: 'sTime',
      valueType:'dateRange',
      width:110,
      hideInTable:true,
      hideInSearch:activeKey=='tab1',
    },
    {
      title: '打款日期',
      dataIndex: 'refundTime',
      width:110,
      valueType:'date',
      hideInTable:activeKey!='tab3',
      hideInSearch:true,
    },
    {
      title: '订单总金额',
      dataIndex: 'totalAmount',
      hideInSearch:true,
      width: 120,
      valueType:'money',
    },
    {
      title: '订单实际金额',
      dataIndex: 'totalActualAmount',
      hideInSearch:true,
      hideInTable:activeKey=='tab1'||activeKey=='tab4',
      width: 120,
      valueType:'money',
    },
    {
      title: '服务费',
      hideInSearch:true,
      dataIndex: 'totalRefundAmount',
      hideInTable:activeKey=='tab1'||activeKey=='tab4',
      width: 120,
      valueType:'money',
    },
    {
      title: "操作",
      valueType: 'option',
      width:120,
      render: (text, record:any,_, action) => [
        <a
        key="detail"
        onClick={async() => {
            var val = await findDetailBySettlementId({settlementId:record.id})
            if (val.errorCode === '200') {
              //获取关联的服务商
              var param = {dealerId:record.dealerId}
              var val2 = await findServiceDealer(param)
              if (val.errorCode === '200') {
                setServices(val2.data)
                setCurrentRecord(record)
                var pIndex=0
                val.data.forEach((element:any) => {
                  pIndex=pIndex+1
                  element.pIndex = pIndex
                  if(activeKey=='tab1'){
                    element.a_price = element.price
                  }else{
                    element.a_price = element.actualPrice
                  }
                });
                var data = val.data
                if(activeKey=='tab1'){
                  setEditableRowKeys(data.map((item: any) => item.pIndex));
                }else{
                  setEditableRowKeys([]);
                }
                var price = (accMul(accSub(data.reduce(function (total, currentValue, currentIndex, arr) {
                  return  accAdd (total, accMul(currentValue['orderNum'],Number(currentValue['price']))) ;
                }, 0),data.reduce(function (total, currentValue, currentIndex, arr) {
                  return  accAdd (total, accMul(currentValue['orderNum'],Number(currentValue['a_price']))) ;
                }, 0)),0.85))
                formRef.current.setFieldsValue({"serviceFee":-Number(price)});
                setProData(data)
                setShowDetail(true);
            }else{
              message.error('获取服务商失败')
            }
            }else{
              message.error('获取订单失败')
            }
        }}
      >
        {activeKey=='tab1'?'结算':'详情'}
      </a>,
      <a   key="file" hidden={activeKey!='tab5'} onClick={()=>{
          setShowFile(true)
      }}>附件查看</a>
    ]
    }
  ];
  
  const changeState=async(status:string,keys:any)=>{
    var val = await setStatus({settlementStatus:status,ids:keys})
    if (val.errorCode === '200') {
      message.success('设置成功')
      actionRef.current?.reloadAndRest?.();
    }else{
      message.error(val.errorMessage);
    }

  }

  const getButtons=(selectedRowKeys:any)=>{
    if(activeKey=='tab1'){
      return <>
         <Popconfirm title='确定要删除吗?' key='delete' onConfirm={async() => {
              changeState('5',selectedRowKeys)
            }}>
              <a key="i1">删除</a>
         </Popconfirm>
         <a key="i2" onClick={()=>{setShowVouchern(true)}}>修改凭证</a>
         <a key="i3" onClick={()=>{
                  setShowService(true)
            }}>修改服务商</a>
      </>
    }else  if(activeKey=='tab2'){
      return <>
       <a key="i2" onClick={()=>{setShowVouchern(true)}}>修改凭证</a>
       <a key="i01" onClick={()=>{
                  changeState('1',selectedRowKeys)
            }}>重置为未结算</a>
       <a key="i02" onClick={()=>{
                  changeState('3',selectedRowKeys)
            }}>已确认</a>
      </>
    }else  if(activeKey=='tab5'){
      return <>
          <a key="i03"  onClick={()=>{
                  changeState('2',selectedRowKeys)
            }}>重置为已结算</a>
          <a key="i04"   onClick={()=>{
                  changeState('4',selectedRowKeys)
            }}>已打款</a>
      </>
    }else  if(activeKey=='tab3'){
      return <>
          <a key="i03"  onClick={()=>{
                  changeState('3',selectedRowKeys)
            }}>重置为已确认</a>
      </>
    }else  if(activeKey=='tab4'){
      return <>
          <Popconfirm title='确定要撤回吗?' key='delete' onConfirm={async() => {
              changeState('1',selectedRowKeys)
            }}>
            <a key="i26">撤回</a>
            </Popconfirm>
       </>
    }
    return <>
      
         
           
       
          
           
        
           <a key="i25" hidden={activeKey!='tab3'} onClick={()=>{
                changeState('3',selectedRowKeys)
            }}>重置为已确认</a>
           
    </>
  }

  return (
    <PageContainer>
    <ProTable
      headerTitle=''
      pagination={{
        pageSizeOptions:['20', '100', '500']
      }}
      actionRef={actionRef}
      tableAlertOptionRender={({selectedRowKeys,onCleanSelected}) => {
        return (
          <Space size={16}>
            <a key="i2" style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
            {getButtons(selectedRowKeys)}
          </Space>
        );
      }}
      rowSelection={{
        selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
      }}
      scroll={{x:1200}}
      request ={async(params, sorter, filter) => {
        if(activeKey=='tab1'){
          params.settlementStatus = '1'
        }else  if(activeKey=='tab2'){
          params.settlementStatus = '2'
        }else  if(activeKey=='tab3'){
          params.settlementStatus = '4'
        }else  if(activeKey=='tab4'){
          params.settlementStatus = '5'
        }else if(activeKey=='tab5'){
          params.settlementStatus = '3'
        }
        if(params.oTime&&params.oTime.length>0){
          params.orderBeginTime = params.oTime[0]
          params.orderEndTime = params.oTime[1]
          params.oTime = undefined;
        }
        if(params.sTime&&params.sTime.length>0){
          params.settlementBeginTime = params.sTime[0]
          params.settlementEndTime = params.sTime[1]
          params.sTime = undefined;
        }
        return findOrderSettlementList({ ...params, sorter, filter })
      }}
      columns={columns}
      rowKey="id"
      search={{span:6}}
      toolbar={{
        menu: {
          type: 'tab',
          activeKey: activeKey,
          items: [
            {
              key: 'tab1',
              label: <span>未结算</span>,
            },
            {
              key: 'tab2',
              label: <span>已结算</span>,
            },
            {
              key: 'tab5',
              label: <span>已确认</span>,
            },
            {
              key: 'tab3',
              label: <span>已打款</span>,
            },
            {
              key: 'tab4',
              label: <span>已删除</span>,
            },
          ],
          onChange: (key) => {
            setActiveKey(key as string);
            actionRef.current?.reloadAndRest?.();
          },
        },
        settings: [],
      }}
      />
      
       <DrawerForm title='详情' width={1200} visible={showDetail}  formRef={formRef} onVisibleChange={v=>{setShowDetail(v)}}
          submitter={{
            searchConfig: {
              submitText: '结算',
              resetText: '取消'
            },
            render: (props, defaultDoms) => {
              return activeKey=='tab1'?[...defaultDoms]:[]
            }
          }} 
       onFinish={async(value)=>{
        console.log(value)
        value.id = currentRecord.id
        // value.orderNumber = currentRecord.orderNumber
        // value.orderId = currentRecord.orderId
        // value.dealerId=currentRecord.dealerId
        // value.dealerName = currentRecord.dealerName
        // value.serviceName = services.filter((item:any)=>item.serviceId==value.serviceId)[0].serviceName
        // value.dealerCode = currentRecord.dealerCode
        var t1 = proData.reduce(function (total, currentValue, currentIndex, arr) {
          return  accAdd (total, accMul(currentValue['orderNum'],Number(currentValue['price']))) ;
        }, 0)
        var t2 = proData.reduce(function (total, currentValue, currentIndex, arr) {
          return  accAdd (total, accMul(currentValue['orderNum'],Number(currentValue['a_price']))) ;
        }, 0)
        value.totalAmount = t1
        value.totalActualAmount = t2
        value.totalDifferenceAmount = accSub(t2,t1)
        value.totalRefundAmount = accMul(accSub(t2,t1),0.85)
        var flag = false
        value.settlementStatus = 2
        value.details = proData.map((item:any)=>{
          if(item.a_price == undefined){
            flag=true
          }
          var t1 = accMul(Number(item.price), item.orderNum)
          var t2 = accMul(Number(item.a_price), item.orderNum)
          return {
            id:item.id,
            productId:item.productId,
            productName:item.productName,
            productStandard:item.productStandard,
            orderNum:item.orderNum,
            price:item.price,
            actualPrice:item.a_price,
            totalPrice:t1,
            totalActualPrice:t2,
            differenceAmount:accSub(t2,t1),
            refundAmount: accMul(accSub(t2,t1),0.85),
            isGift:item.isGift
          }
        })
        if(flag){
          message.warning('请填写实际单价');
          return false
        }
        var val = await editSettlementDetail(value)
        if (val.errorCode === '200') {
          actionRef.current?.reloadAndRest?.();
          return true
        }else{
          message.error(val.errorMessage);
          return false
        }
       }}
        drawerProps={{
          destroyOnClose:true,
          forceRender:true
        }}>
           <EditableProTable  headerTitle="产品列表" rowKey='pIndex' columns={pColumns} value={proData} search={false} toolbar={{
            settings: []
        }} recordCreatorProps={false} onChange={data => {
            setEditableRowKeys(data.map((item: any) => item.pIndex));
            setProData(data);
        }} pagination={false} editable={{
            editableKeys,
            type: 'multiple',
            onChange: setEditableRowKeys,
            onValuesChange: (record, recordList) => {
              setProData(recordList);
              var price = (accMul(accSub(recordList.reduce(function (total, currentValue, currentIndex, arr) {
                return  accAdd (total, accMul(currentValue['orderNum'],Number(currentValue['price']))) ;
              }, 0),recordList.reduce(function (total, currentValue, currentIndex, arr) {
                return  accAdd (total, accMul(currentValue['orderNum'],Number(currentValue['a_price']))) ;
              }, 0)),0.85))
              formRef.current.setFieldsValue({"serviceFee":-Number(price)});
            },
            actionRender: (row, config, defaultDoms) => {
            return [];
            }
        }} summary={pageData => {
          return <>
                  <Table.Summary.Row style={{backgroundColor:'#fafafa'}}>
                    <Table.Summary.Cell index={1} colSpan={2} align='center'>订单总金额</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={2} align='center'>实际总金额</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={2} align='center'>订单总差额</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={3} align='center'>返利总金额</Table.Summary.Cell>
                  </Table.Summary.Row>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={2} align='center'>
                      {moneyFormat(proData.reduce(function (total, currentValue, currentIndex, arr) {
                            return  accAdd (total, accMul(currentValue['orderNum'],Number(currentValue['price']))) ;
                          }, 0)) }
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={2} align='center'>
                    {moneyFormat(proData.reduce(function (total, currentValue, currentIndex, arr) {
                        return  accAdd (total, accMul(currentValue['orderNum'],Number(currentValue['a_price']))) ;
                      }, 0))}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={2} align='center'>
                    {moneyFormat(-accSub(proData.reduce(function (total, currentValue, currentIndex, arr) {
                        return  accAdd (total, accMul(currentValue['orderNum'],Number(currentValue['price']))) ;
                      }, 0),proData.reduce(function (total, currentValue, currentIndex, arr) {
                        return  accAdd (total, accMul(currentValue['orderNum'],Number(currentValue['a_price']))) ;
                      }, 0)))}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={3} align='center'>
                    {moneyFormat(-accMul(accSub(proData.reduce(function (total, currentValue, currentIndex, arr) {
                        return  accAdd (total, accMul(currentValue['orderNum'],Number(currentValue['price']))) ;
                      }, 0),proData.reduce(function (total, currentValue, currentIndex, arr) {
                        return  accAdd (total, accMul(currentValue['orderNum'],Number(currentValue['a_price']))) ;
                      }, 0)),0.85))}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                 
                 </>}}></EditableProTable>
                <div style={{marginLeft:20,marginTop:20}}>
                      {
                        activeKey=='tab1'?
                        <>
                          <ProForm.Group>
                            <ProFormSelect rules={[{ required: true}]}  initialValue={services.length>0&&services.filter((item:any)=>item.isActive=='1').length>0?services.filter((item:any)=>item.isActive=='1')[0].serviceId:''} name="serviceId" label="服务商" width="md" options={services.map((item:any)=>{
                              return {label:item.serviceName,value:item.serviceId}
                            })}/>
                            </ProForm.Group>
                            <ProForm.Group>
                                  <ProFormDigit min={-100000000} name="serviceFee" label="服务费" width="md" />
                            </ProForm.Group>
                            <ProForm.Group>
                                  <ProFormTextArea name="remark" label="备注" width="lg" fieldProps={{showCount:true,maxLength:500}} />
                            </ProForm.Group>
                        </>:
                        <>
                          <UpDownLabel title='服务商' texts={[currentRecord.serviceName]}/>
                          <UpDownLabel title='服务费' texts={[currentRecord.totalRefundAmount]}/>
                          <UpDownLabel title='备注' texts={[currentRecord.remark]}/>
                        </>
                      }
                </div>
       </DrawerForm>
       <Drawer title='详情' style={{zIndex:99}} width={1200} onClose={()=>setShowService(false)} visible={showService} destroyOnClose={true} forceRender={true}>
          <ProTable pagination={false} search={false}   rowKey="serviceId"   dataSource = {services}
            columns={sColumn} toolbar={{settings:[]}} >

          </ProTable>
       </Drawer>
       <Drawer title='凭证列表' style={{zIndex:99}} width={1200} onClose={()=>setShowVouchern(false)} visible={showVouchern} destroyOnClose={true} forceRender={true}>
          <ProTable pagination={false} search={false}   rowKey="id"   dataSource = {vouchern}
            columns={vColumn} toolbar={{settings:[]}} >

          </ProTable>
       </Drawer>
       <Drawer
            width={1000}
            title='详情'
            visible={showFile}
            onClose={()=>setShowFile(false)}
            destroyOnClose={true}>
               <Upload   fileList={[{},{}]}  onPreview={handlePreview} showUploadList={{showRemoveIcon:false}}>
              </Upload>
      </Drawer>
  </PageContainer>
  );
};